package com.xb.system.controller;


import com.xb.model.domain.dto.*;
import com.xb.model.domain.entity.Userinfo;
import com.xb.model.domain.vo.LoginResponseVO;
import com.xb.system.common.result.Result;
import com.xb.system.service.UserService;
import com.xb.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @PostMapping("/getCaptcha")
    public Result<String> getCaptcha(@RequestBody Map<String, String> request) {
        String phone = request.get("phone");
        String captcha = userService.generateCaptcha(phone);
        return Result.ok(captcha);
    }

    @PostMapping("/userLogin")
    public Result<LoginResponseVO> login(@RequestBody LoginRequestDTO request) {
        Result<LoginResponseVO> result;
        if ("captcha".equals(request.getLoginType())) {
            result = userService.loginByCaptcha(request.getPhone(), request.getCaptcha(), request.getInviterId());
        } else if ("password".equals(request.getLoginType())) {
            result = userService.loginByPassword(request.getPhone(), request.getPassword());
        } else {
            throw new RuntimeException("无效的登录类型");
        }
        return result;
    }

    @PostMapping("/set-password")
    public Result<LoginResponseVO> setPassword(@RequestBody SetPasswordRequestDTO request) {
        userService.setPassword(request.getPhone(), request.getPassword());
        Userinfo userInfo = userService.findByPhone(request.getPhone());
        String token = jwtUtil.generateToken(userInfo.getId());
        LoginResponseVO responseVO = new LoginResponseVO(token, false);
        responseVO.getUser().setPhone(userInfo.getPhone());
        return Result.ok(responseVO);
    }

}